<?php

namespace app\api\controller;

use addons\shopro\listener\activity\Update;
use addons\shopro\model\UserStore;
use app\admin\model\Change;
use app\admin\model\Command;
use app\admin\model\share\CommonShare;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\IM;
use app\common\library\Sms;
use app\common\model\AdvertPriceLog;
use app\common\model\MoneyLog;
use app\common\model\User as FUser;
use \app\admin\model\share\ShareUser;
use app\common\model\User5g;
use app\common\model\White;
use fast\Random;
use think\cache\driver\Redis;
use think\Config;
use think\Db;
use think\Validate;
use linghuo\Linghuo as linghuo;
use linghuo\v2\Linghuo as linghuo2;
use app\common\model\userIdCard;
use app\admin\model\UserWithdraw;
use app\common\library\Auth;
use \addons\shopro\model\Order;
use app\common\model\UserChangeLog;
use addons\shopro\model\UserAddress;


/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third', 'user_in', 'parent_in',
        'check_share', 'new_amount', 'get_order_sum',
        'refund_mutual',
        'user_score', 'role_url', 'role_level', 'user_info','mobileMerchantLogin','bind5g','verification5g','role5g'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }


    /**
     * [realname 实名]
     * @param  [type]     $name           [真实姓名]
     * @param  [type]     $idCard         [身份证号码]
     * @param  [type]     $phone          [手机号码]
     * @param  [type]     $imgIdCardFront [身份证正面图]
     * @param  [type]     $imgIdCardBack  [身份证背面图]
     * @return [type]                     [description]
     * @since  2022-09-24
     */
    public function realname()
    {
        $ws = Db::name("config")->where(['name' => 'withdraw_status'])->find();
        if (!$ws) {
            $this->error(__('提现通道测试，即将开放中'));
        } else {
            if ($ws['value'] == 2) {
                $this->error(__('提现通道测试，即将开放中'));
            }
        }
        $name = $this->request->post("name");
        $idCard = $this->request->post("idCard");
        $phone = $this->request->post("phone");
        $imgIdCardFront = $this->request->post("imgIdCardFront");
        $imgIdCardBack = $this->request->post("imgIdCardBack");
        $IdCardStart = $this->request->post("IdCardStart", '');
        $IdCardEnd = $this->request->post("IdCardEnd", '');
        $addr = $this->request->post("addr", '');
        $bitMax = 2 * 1024 * 1024;
        // $bitMax = 2;
        if (!Validate::is($name, 'chsAlpha')) {
            $this->error(__('Name can not be empty'));
        }
        if (!Validate::max($imgIdCardFront, $bitMax)) {
            $this->error(__('IdCard images front max 2M'));
        }
        if (!Validate::max($imgIdCardBack, $bitMax)) {
            $this->error(__('IdCard images back max 2M'));
        }
        if (!Validate::regex($phone, "^1[3-9][0-9]\d{8}$")) {
            $this->error(__('Mobile is incorrect'));
        }

        if (!Validate::regex($idCard, "(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)")) {
            $this->error(__('ID card error'));
        }

        $option = [
            'user_id' => $this->auth->id,
            'name' => $name,
            'phone' => $phone,
            'imgIdCardFront' => $imgIdCardFront,
            'imgIdCardBack' => $imgIdCardBack,
            'idCard' => strtoupper($idCard),
            'IdCardStart' => $IdCardStart,
            'IdCardEnd' => $IdCardEnd,
            'addr' => $addr,
            'memberId' => '',
            'systemId' => '',
            'createtime' => time(),
            'busType' => linghuo2::BUSTYPE_1,
        ];
        //存在，就修改
        $idCardData = userIdCard::where('user_id', '=', $this->auth->id)->find();
        // 数据库没有 查看服务商有没有
        if (!$idCardData) {
            $res1 = (new linghuo)->query(linghuo::QUERY_TYPE_3, '', $idCard);
            $res2 = (new linghuo2)->getsystemid(Linghuo2::GET_SYSTEM_ID_TYPE_3, $idCard);
            if ($res2['code'] === 1 && $res2['data']['result']['systemId']) {
                $option['systemId'] = $res2['data']['result']['systemId'];
            }
            if ($res1['code'] === 1 && $res1['data']['result']['memberId']) {
                $option['memberId'] = $res1['data']['result']['memberId'];
            }
            $idCardData = userIdCard::where('user_id', '=', $this->auth->id)->find();
            // 服务商存在直接添加并完成
            if (!$idCardData && !empty($option['systemId'])) {
                (new userIdCard)->addIdCard($option);
                $this->success(__('Real name successful'));
            }
        }
        if ($idCardData) {
            $res2 = (new linghuo2)->getsystemid(Linghuo2::GET_SYSTEM_ID_TYPE_3, $idCard);
            if (empty($idCardData['systemId']) && $res2['code'] === 1 && $res2['data']['result']['systemId']) {
                $idCardData->systemId = $res2['data']['result']['systemId'];
                $idCardData->save();
            }
            $this->error(__('已实名，无须再次提交'));
        }
        $res = (new linghuo2)->register($name, $idCard, $phone, $imgIdCardFront, $imgIdCardBack);
        if ($res['code'] !== 1) {
            $this->error($res['msg']);
        }
        if ($res['data']['result']['systemId']) {
            $option['systemId'] = $res['data']['result']['systemId'];
        }
        if ($res['data']['result']['memberId']) {
            $option['memberId'] = $res['data']['result']['memberId'];
        }
        $idCardData = userIdCard::where('user_id', '=', $this->auth->id)->find();
        if (!$idCardData) {
            (new userIdCard)->addIdCard($option);
        }
        $this->success(__('real name successful'));
    }

    /**
     * [bindBank description]
     * @param  [type]     $bankPhone  [银行预留电话]
     * @param  [type]     $imgFace  [面部高清图片]
     * @param  [type]     $cardNo  [银行卡号]
     * @param  [type]     $bankName  [银行名称]
     * @param  [type]     $bankNo  [开户行号]
     * @return [type]     [description]
     * @since  2022-09-25
     */
    public function bindBank()
    {
        $bankPhone = $this->request->post("bankPhone");
        $imgFace = $this->request->post("imgFace");

        $cardNo = $this->request->post("cardNo");
        $bankNo = $this->request->post("bankNo");
        $bankName = $this->request->post("bankName");

        $bitMax = 2 * 1024 * 1024;
        // $bitMax = 2;
        if (empty($cardNo)) {
            $this->error(__('cardNo can not be empty'));
        }
        if (empty($bankNo)) {
            $this->error(__('bankNo can not be empty'));
        }
        if (empty($bankName)) {
            $this->error(__('bankName can not be empty'));
        }
        if (!Validate::max($imgFace, $bitMax)) {
            $this->error(__('imgFace images max 2M'));
        }
        if (!Validate::regex($bankPhone, "^1[3-9][0-9]\d{8}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        // $this->auth->id = 1;
        //存在，就修改
        $idCardData = userIdCard::where('user_id', '=', $this->auth->id)->find();
        if (!$idCardData) {
            $this->error(__('Please use your real name'));
        }
        // 数据库没有
        // if ($idCardData && empty($idCardData['bankNo'])) {
        //     $res1 = (new linghuo)->query(linghuo::QUERY_TYPE_1, $idCardData->memberId, $idCardData->idCard);
        //     if ($res1['code'] === 1 && $res1['data']['result']['bankNo']) {
        //         $idCardData->bankNo = $res1['data']['result']['bankNo'];
        //         $idCardData->cardNo = $res1['data']['result']['cardNo'];
        //         $idCardData->bankPhone = $res1['data']['result']['bankPhone'];
        //         $idCardData->bankName = $bankName;
        //         $idCardData->save();
        //     }
        // }
        // 开户
        // $card = (new linghuo)->query(linghuo::QUERY_TYPE_2, $idCardData->memberId);

        //未开户或开户失败
        // if ($card['code'] === 1 && in_array($card['data']['result']['acctStatus'], ['0', '3'])) {
        //     $res = (new linghuo)->bank($idCardData['memberId'], $bankNo, $cardNo, $bankPhone, $imgFace);
        //     if ($res['code'] !== 1) {
        //         $this->error($res['msg']);
        //     }
        $idCardData->imgFace = $imgFace;
        //     $idCardData->save();
        // }
        // var_dump($idCardData['bankNo']);exit;
        $error = '';
        $card = (new linghuo2)->query($idCardData['systemId']);//
        // 取出原来的卡号
        if ($card['code'] === 1) {
            $oldupdate = false;
            if (!empty($card['data']['result']['bankNo']) && $card['data']['result']['bankNo'] != $idCardData['bankNo']) {
                $oldupdate = true;
                $idCardData->bankNo = $card['data']['result']['bankNo'];
            }
            if (!empty($card['data']['result']['cardNo']) && $card['data']['result']['cardNo'] != $idCardData['cardNo']) {
                $oldupdate = true;
                $idCardData->cardNo = $card['data']['result']['cardNo'];
            }
            if (!empty($card['data']['result']['bankPhone']) && $card['data']['result']['bankPhone'] != $idCardData['bankPhone']) {
                $oldupdate = true;
                $idCardData->bankPhone = $card['data']['result']['bankPhone'];
            }
            if ($oldupdate) {
                $idCardData->bankName = $bankName;
                $idCardData->save();
            }

        }
        // 银行卡修改
        if ($bankNo != $idCardData['bankNo'] || $cardNo != $idCardData['cardNo'] || $bankPhone != $idCardData['bankPhone']) {
            $updateRes = (new linghuo2)->update($idCardData['systemId'], $bankNo, $cardNo, $bankPhone);
            if ($updateRes['code'] !== 1) {
                $this->error($updateRes['msg']);
                // $this->error(__('Update bankCard error：') . $updateRes['msg']);
            }
            $idCardData->bankNo = $bankNo;
            $idCardData->cardNo = $cardNo;
            $idCardData->bankPhone = $bankPhone;
            $idCardData->bankName = $bankName;
            $idCardData->save();
        }
        $this->success(__('Bind bank successful'));
    }

    /**
     * [cardinfo description]
     * @return [type]     [description]
     * @since  2022-09-25
     */
    public function cardinfo()
    {
        $idCardData = userIdCard::where('user_id', '=', $this->auth->id)->find();
        $this->success('成功', $idCardData ?? new \stdClass());
    }

    /**
     * [withdraw 提现]
     * @param  [type]     $type  [提现类型 类型:0=银行卡]
     * @param  [type]     $money  [金额]
     * @return [type]     [description]
     * @since  2022-09-25
     */
    public function withdraw()
    {
        $pattern = Db::name("config")->where(['name'=>'pattern'])->value('value');
        if($pattern == 3){
            $ll_where['user_id'] = $this->auth->id;
            $ll_where['status'] = ['in', '1,2'];
            $ll_where['pay_fee'] = ['>', 100];
            $ll_where['share_retreat'] = ['neq', 2];
            $ll_data = Db::name("shopro_order")->where($ll_where)->find();
            if(!$ll_data){
                $this->error(__('当前是准推广员，成为正式推广员才能提现!'));
            }
        }
        $w = date('w');
        if ($w == 0 || $w == 6) {
            $this->error(__('亲，现在是非工作日，请在工作日提现，谢谢！'));
        }
        $withdraw_start_time = Db::name("config")->where(['name' => 'withdraw_start_time'])->value("value");
        $withdraw_end_time = Db::name("config")->where(['name' => 'withdraw_end_time'])->value("value");
        if(!$withdraw_start_time || !$withdraw_end_time){
            $withdraw_start_time = "9:01";
            $withdraw_end_time = "18:01";
        }
        $time = date("H:i");
        if(strtotime($time)<strtotime($withdraw_start_time) || strtotime($time)>strtotime($withdraw_end_time)){
            $this->error("提现时间为".$withdraw_start_time."~".$withdraw_end_time);
        }
        $ws = Db::name("config")->where(['name' => 'withdraw_status'])->find();
        if (!$ws) {
            $this->error(__('提现通道测试，即将开放中'));
        } else {
            if ($ws['value'] == 2) {
                $this->error(__('提现通道测试，即将开放中'));
            }
        }
        $domain = $this->request->domain();
        if ($domain == 'https://zhongjunf.bigchun.com') {
            // $this->error(__('暂不支持提现'));
        }
        //qi11.1
        $m_day = strtotime('-30 day');
        $r_where['user_id'] = $this->auth->id;
        $r_where['createtime'] = ['>', $m_day];
        $r_where['one_day'] = 1;
        $r_where['status'] = ['in', '1,2'];
        $r_where['share_retreat'] = ['neq', 2];
        $r_data = Db::name("shopro_order")->where($r_where)->find();

        $one_day_order = 1;
        $c_data = Db::name("config")->where(['name' => 'withdraw_sta', 'value' => 1])->find();//中慧特殊配置
        $team_withdraw_status = Config::get('site.team_withdraw_status') ? Config::get('site.team_withdraw_status') : 1;
        if (1 == $team_withdraw_status && empty($r_data)) {
            $share_data = Db::name("share_user")->where(['user_id' => $this->auth->id])->find();
            $one_day_order = 0;
            if ($c_data && $share_data['is_order'] == 0) {//中慧新客户不限制
                $one_day_order = 1;
            }

        }
        if ($one_day_order == 0) {//注册30天内不用购买也能提现
            $c_data = Db::name("config")->where(['name' => 'reg_with_time'])->find();
            if (isset($c_data)) {
                $reg_with_time = $c_data['value'];
            } else {
                $reg_with_time = 30;
            }
            $cha_time = time() - $reg_with_time * 60 * 60 * 24;
            if ($cha_time > $this->auth->createtime) {
                $one_day_order = 0;
            } else {
                $one_day_order = 1;
            }
        }
        if ($one_day_order == 0) {
            //后台设置的用户不限制
            $with_mobile = Db::name("config")->where(['name' => 'with_mobile'])->find();
            if ($with_mobile && $with_mobile['value']) {
                $str_status = strstr($with_mobile['value'], ",");
                if ($str_status) {
                    $mobiles = explode(',', $with_mobile['value']);
                    if (in_array($this->auth->mobile, $mobiles)) {
                        $one_day_order = 1;
                    }
                } else {
                    if ($this->auth->mobile == $with_mobile['value']) {
                        $one_day_order = 1;
                    }
                }

            }
        }
        if ($one_day_order == 0) {
            $this->error("购买一次每月一品才能提现");
        }

        // $this->auth->id = 1;
        $type = $this->request->post("type", '0');
        $with_type = $this->request->post("with_type", '0');//0正常1老提现2广告收益提现3零批收益
        $money = $this->request->post("money");
        $captcha = $this->request->post("captcha");//短信验证码
        if (!$captcha) {
            $this->error(__('验证码不能为空'));
        }

        $user = $this->auth->getUser();
        if (!White::verifyMobileWhite($this->auth->mobile, $captcha)) {
            $arr_temp = array(13131388888,
                18213345601, 18213345602, 18213345603, 18213345604, 18213345605, 18213345606, 18213345607, 18213345608, 18213345609, 18213345610, 18213345611, 18213345612, 18213345613, 18213345614, 18213345615, 18213345616, 18213345617, 18213345619, 18213345620, 18213345621, 18213345622, 18213345623, 18213345624, 18213345625, 18213345626, 18213345627, 18213345628, 13136281919
            );
            $is_true = true;
            if (in_array($this->auth->mobile, $arr_temp)) {
                if ($this->auth->mobile == '13131388888' && $captcha == '131313') {
                    $is_true = false;
                }
                if ($this->auth->mobile != '13131388888' && $captcha == '1111') {
                    $is_true = false;
                }
            }
            $config_test_code = Db::name("config")->where(['name' => "test_code"])->find();
            $test_code = $config_test_code ? $config_test_code['value'] : 134913;
            if ($is_true) {
                if ($user->staff == 2 && $captcha != $test_code) {
                    $this->error(__('验证码不正确'));
                }
                if ($user->staff != 2) {
                    if (!Sms::check($this->auth->mobile, $captcha, 'transferpoints')) {
                        $this->error(__('验证码不正确'));
                    }
                }
            }
        }
        //最少提现金额
        $with_less_money = Db::name("config")->where(['name' => 'with_less_money'])->find();
        if($with_less_money){
            $with_less_money = $with_less_money['value'];
        }else{
            $with_less_money = 10;
        }
        if ($money < $with_less_money) {
            $this->error(__('最少提现'.$with_less_money));
        }
        $idCardData = userIdCard::where('user_id', '=', $this->auth->id)->find();
        if (!$idCardData || empty($idCardData['idCard']) || empty($idCardData['cardNo'])) {
            $this->error(__('Please use your real name and bind your bank card'));
        }
        if ($type != UserWithdraw::TYPE_0) {
            $this->error(__('Withdraw type bank'));
        }

        if ($money > 300 && $with_type == 1) {
            $this->error('每次最多提现300');
        }
        if ($money > 2000) {
            $this->error('每次最多提现2000');
        }
        $star_time = date('Y-m-d 00:00:00');
        $end_time = date('Y-m-d 23:59:59');
        $w_data = (new UserWithdraw)
            ->where('auditStatus', 'in', '0,1')
            ->where('createtime', 'between time', [$star_time, $end_time])
            ->where(['user_id' => $this->auth->id])
            //->where(['with_type' => $with_type])
            ->find();
        if ($w_data) {
            $this->error('每天最多提现1次');
        }
        $exists = UserWithdraw::where('user_id', '=', $this->auth->id)->where('payType', 'in', [UserWithdraw::PAY_TYPE_0, UserWithdraw::PAY_TYPE_1])
            ->where('auditStatus', 'in', [0, 1])->where(['with_type' => $with_type])->find();
        if ($exists) {
            $this->error(__("You haven't finished your withdrawal"));
        }
        //提现总金额限制
        $with_money = Db::name("config")->where(['name' => "with_money"])->find();
        $with_sum_money = $with_money ? $with_money['value'] : 6250;
        $money_sum = (new UserWithdraw)
            ->where('auditStatus', 'in', '0,1')
            ->where('createtime', 'between time', [$star_time, $end_time])
            ->sum("money");
        if (($money_sum + $money) > $with_sum_money) {
            $this->error('亲，因今日银行提现额度已满，请明天再提。');
        }
        $shareUserData = ShareUser::where('user_id', '=', $this->auth->id)->find();
        if($shareUserData['is_with'] == 1){
            $this->error('提现通道通道受阻，请联系客服');
        }
        if ($with_type == 1) {
            $old_price_with = Db::name("config")->where(['name' => 'old_price_with'])->find();
            if (!isset($old_price_with) || $old_price_with['value'] != 1) {
                if (($shareUserData['role'] == 1 || $shareUserData['role'] == 2) && $shareUserData['old_price'] >= 1000) {
                    $this->error('您的账号被系统检测异常，暂做冻结处理，如有异议，请联系项目负责人申诉');
                } elseif ($shareUserData['role'] >= 3) {
                    $this->error('为了支持2.0全新起航、一星及以上负责人、老余额可以选择每月一品或转中军值兑换股票。');
                }
            }
        }
        // 启动事务
        \think\Db::startTrans();
        $money = floatval($money);
        try {

            if ($with_type == 1) {
                $price = floatval($shareUserData->old_price);
            } elseif ($with_type == 2) {
                $price = floatval($shareUserData->advert_price);
            } elseif ($with_type == 3) {
                $price = floatval($shareUserData->lp_price);
            } else {
                $price = floatval($shareUserData->price);

            }

            if ($price < $money) {
                throw new \Exception(sprintf(__("Cash withdrawal is allowed at most %s"), $price));
            }
            //添加提现订单

            if ($user->staff == 2) {
                $option = [
                    'user_id' => $this->auth->id,
                    'username' => $this->auth->username,
                    'type' => $type,
                    'money' => $money,
                    'memberId' => $idCardData['memberId'],
                    'systemId' => $idCardData['systemId'],
                    'createtime' => time(),
                    'bankName' => $idCardData['bankName'],
                    'cardNo' => $idCardData['cardNo'],
                    'order_sn' => UserWithdraw::getSn($this->auth->id),
                    'memberName' => $idCardData['name'],
                    'idCard' => $idCardData['idCard'],
                    'auditMsg' => "测试用",
                    'auditStatus' => 2,//审核状态:0=未审核,1=审核通过,2=审核驳回
                    'with_type' => $with_type,
                ];
            } else {
                $option = [
                    'user_id' => $this->auth->id,
                    'username' => $this->auth->username,
                    'type' => $type,
                    'money' => $money,
                    'memberId' => $idCardData['memberId'],
                    'systemId' => $idCardData['systemId'],
                    'createtime' => time(),
                    'bankName' => $idCardData['bankName'],
                    'cardNo' => $idCardData['cardNo'],
                    'order_sn' => UserWithdraw::getSn($this->auth->id),
                    'memberName' => $idCardData['name'],
                    'idCard' => $idCardData['idCard'],
                    'with_type' => $with_type,
                ];
            }
            // var_dump($option);exit;
            // $shareUserData->price -= $money;
            // $shareUserData->lock_money += $money;

            (new UserWithdraw)->addWithdraw($option);
            $after = $shareUserData['price'] - abs($money);
            if ($user->staff == 2) {
                if ($with_type == 1) {
                    $after = $shareUserData['old_price'] - abs($money);
                    MoneyLog::create(['user_id' => $this->auth->id, 'money' => abs($money), 'before' => $shareUserData['old_price'], 'after' => $after, 'type' => 6, 'memo' => "提现,测试用", 'is_old' => 1]);
                } elseif ($with_type == 2) {
                    $after = $shareUserData['advert_price'] - abs($money);
                    AdvertPriceLog::create(['user_id' => $this->auth->id, 'money' => abs($money), 'before' => $shareUserData['advert_price'], 'after' => $after, 'type' => 3, 'memo' => '提现测试']);
                } elseif ($with_type == 3) {
                    $after = $shareUserData['lp_price'] - abs($money);
                    MoneyLog::create(['user_id' => $this->auth->id, 'money' => abs($money), 'before' => $shareUserData['lp_price'], 'after' => $after, 'type' => 6, 'memo' => "提现,测试用", 'is_old' => 2]);
                } else {
                    MoneyLog::create(['user_id' => $this->auth->id, 'money' => abs($money), 'before' => $shareUserData['price'], 'after' => $after, 'type' => 6, 'memo' => "提现,测试用"]);
                }
                $shareUserData->lock_money($shareUserData, $money, $with_type);
                //开始记录提现驳回
                $shareUserOne = \app\admin\model\share\ShareUser::where('user_id', '=', $user->id)->find();
                $staff = 2;
                $shareUserOne->unlock_money($shareUserOne, abs($money), $shareUserOne::UNLOCK_MONEY_TRUE, $staff, $with_type);
            } else {
                if ($with_type == 1) {
                    $after = $shareUserData['old_price'] - abs($money);
                    MoneyLog::create(['user_id' => $this->auth->id, 'money' => abs($money), 'before' => $shareUserData['old_price'], 'after' => $after, 'type' => 6, 'memo' => "提现", 'is_old' => 1]);
                } elseif ($with_type == 2) {
                    $after = $shareUserData['advert_price'] - abs($money);
                    AdvertPriceLog::create(['user_id' => $this->auth->id, 'money' => abs($money), 'before' => $shareUserData['advert_price'], 'after' => $after, 'type' => 3, 'memo' => '提现']);
                } elseif ($with_type == 3) {
                    $after = $shareUserData['lp_price'] - abs($money);
                    MoneyLog::create(['user_id' => $this->auth->id, 'money' => abs($money), 'before' => $shareUserData['lp_price'], 'after' => $after, 'type' => 6, 'memo' => "提现,测试用", 'is_old' => 2]);
                } else {
                    MoneyLog::create(['user_id' => $this->auth->id, 'money' => abs($money), 'before' => $shareUserData['price'], 'after' => $after, 'type' => 6, 'memo' => "提现"]);
                }
                $shareUserData->lock_money($shareUserData, $money, $with_type);
            }

            // 提交事务
            \think\Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            \think\Db::rollback();
            $this->error(__($e->getMessage()));
        }


        $this->success(__('Withdraw successful'));
    }

    public function withdrawlist()
    {
        $date = $this->request->param("date",'','trim');
        if(!$date){
            $timestamp = strtotime( date("Y-m",time()) );
            $mdays = date( 't', $timestamp );//获取当前月份天数
            $starttime = date( 'Y-m-01 00:00:00', $timestamp );
            $endtime= date( 'Y-m-' . $mdays.' 23:59:59' , $timestamp );
        }elseif ($date){
            $timestamp = strtotime( $date );
            $mdays = date( 't', $timestamp );//获取当前月份天数
            $starttime = date( 'Y-m-01 00:00:00', $timestamp );
            $endtime= date( 'Y-m-' . $mdays.' 23:59:59' , $timestamp );
        }
        $srart = strtotime($starttime);
        $end = strtotime($endtime);
        $with_type = $this->request->post("with_type", '0');//0正常1老提现2广告收益提现3零批收益
        $list = UserWithdraw::where('user_id', '=', $this->auth->id)
            ->where(['with_type'=>$with_type])
            ->whereBetween("createtime",[$srart,$end])
            ->field('money,service_money,pay_money,order_sn,orderNo,payNo,payType,auditStatus,auditMsg,createtime,bankName,cardNo')
            ->order("id desc")
            ->select();
        foreach ($list as $k => $v) {
            $list[$k]['cardNo'] = "****" . substr($v['cardNo'], -4);
            if($v['auditStatus']==0){
                $v['audit_status_text'] = "未审核";
            }
            if($v['payType']==0){
                $v['pay_type_text'] = "未支付";
            }
            $v['reason_text'] = "";
            if ($v['auditMsg']==2&&$v['payType']==2){
                $v['pay_type_text'] = "支付成功";
                $v['audit_status_text'] = "审核失败";
                $v['reason_text'] = "系统维护中";
            }else if($v['payType']==2&&$v['auditStatus']==1){
                $v['pay_type_text'] = "支付成功";
                $v['audit_status_text'] = "审核通过";
                $v['reason_text'] = "";
            }elseif ($v['payType']==3&&$v['auditStatus']==1){
                //审核通过，支付失败的   真是驳回  真实原因
                $v['pay_type_text'] = "支付失败";
                $v['audit_status_text'] = "审核通过";
                $v['reason_text'] = $v['auditMsg'];
            }
        }
        $this->success('', $list);
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account 账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }

        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            User5g::reg5gUser($this->auth->getUser());
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        $type = $this->request->post('type');
        $password = $this->request->post('password');
        // 邀请码
        $invitecode = $this->request->post('invitecode');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $staff = 0;
        $config_test_code = Db::name("config")->where(['name' => "test_code"])->find();
        $test_code = $config_test_code ? $config_test_code['value'] : 134913;
        if ($captcha != '1111') {
            if($captcha != substr($mobile,-4)){//验证是手机后四位不做验证
                if (!Sms::check($mobile, $captcha, 'mobilelogin') && $captcha != $test_code) {
                    $this->error(__('Captcha is incorrect'));
                }
            }

            if ($captcha == $test_code) {
                $staff = 2;//账号类型:0=正常,1=特殊,2=测试
            }
        }

        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if (!empty($type)) {
                $this->error(__('已注册，请先去登录'));
            }
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $temp_data = array();
            if (empty($type)) {
                $this->error(__('未注册，请先去注册'));
            }
            //邀请码
            $temp_data['invitecode'] = $mobile;//邀请码改成手机号$this->english_num();
            if (!$invitecode) {
                $this->error(__('请输入邀请码'));
            }
            /* $p_user = FUser::getByInvitecode($invitecode);
             if (empty($p_user)) {*/
            $p_user = Db::name("user")->where(['mobile' => $invitecode])->find();
            if (!$p_user) {
                $this->error(__('请输入正确的邀请码'));
            }
            $share_user = Db::name("share_user")->where(["user_id" => $p_user['id']])->find();
            if ($share_user['role'] == 0) {
                $this->error(__('该账户暂无邀请权限'));
            }

            //}
            $user_sta = Db::name("user")->where(['id' => $p_user['id']])->find();
            $parent_mobile = $user_sta['parent_mobile'];
            if ($parent_mobile && $parent_mobile != '') {
                $pa_data = Db::name("user")->where(['mobile' => $parent_mobile])->find();
                if (!$pa_data) {
                    $this->error(__('手动设置用户不存在'));
                }
                $pa_count = Db::name("share_user")->where(['parent_id' => $pa_data['id']])->count();
                if ($pa_count >= 3) {
                    // $this->error(__('手动设置用户下级已满'));
                }
                //$get_parent_id = $pa_data['id'];
                $get_parent = (new ShareUser())->get_parent_id_two($pa_data['id']);
                $get_parent_id = empty($get_parent) ? 0 : $get_parent[0];
                $role_type = empty($get_parent) ? 0 : $get_parent[1];
                if ($get_parent_id == 0) {
                    $this->error("邀请码已满额");
                }
            } else {
                $get_parent = (new ShareUser())->get_parent_id_two($p_user['id']);
                $get_parent_id = empty($get_parent) ? 0 : $get_parent[0];
                $role_type = empty($get_parent) ? 0 : $get_parent[1];
                if ($get_parent_id == 0) {
                    $this->error("邀请码已满额");
                }
            }
            /* $get_parent = (new ShareUser())->get_parent_id($p_user['id']);
             $get_parent_id = empty($get_parent) ?  0 : $get_parent[0];
             $role_type = empty($get_parent) ?  0 : $get_parent[1];
             if ($get_parent_id  == 0) {
                 $this->error("邀请码已满额");
             }*/
            /* $temp_data['pid'] = $p_user['id'];
             $temp_data['parent_user_id'] = $get_parent_id;*/

            $temp_data['pid'] = $get_parent_id;
            $temp_data['parent_user_id'] = $p_user['id'];
            $temp_data['role_type'] = $role_type + 1;
            if ($p_user['staff'] == 2 && $staff == 0) {
                $this->error("测试账号下不能注册正式账号！");
            }
            $ret = $this->auth->register($mobile, $password, '', $mobile, $temp_data, $staff);
        }
        $item = Db::name('user')->where('mobile', $mobile)->find();
        /*$params = [
            'mobile' => $mobile,
            'salt' => $item['salt'],
            'password' => $item['password']
        ];
        $url = config('dsh_yuming') . '/api/Futurethree/login';
        $data = postCurl($url, $params);
        if ($data['data']['code'] == 1) {
            $redis = new Redis();
            $redis->set('dshtoken_' . $item['id'], $data['data']['data']['token']);
        }*/
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 验证手机号是否是当前用户下下面
     */
    public function parent_mobile()
    {
        $user = $this->auth->getUser();
        $parent_mobile = $this->request->post('parent_mobile', '');
        if (!$parent_mobile || empty($parent_mobile) || $parent_mobile == '' || !isset($parent_mobile)) {
            $s_sta = Db::name("user")->where(['id' => $user->id])->update(['parent_mobile' => '']);
            if ($s_sta !== false) {
                $this->success("通过");
            } else {
                $this->error('失败');
            }
        }


        $pa_data = Db::name("user")->where(['mobile' => $parent_mobile])->find();
        $share_user_data = Db::name("share_user")->where(['user_id' => $pa_data['id']])->find();
        /*//一级
        if($share_user_data['parent_id'] == $user->id){
            $s_sta = Db::name("user")->where(['id'=>$user->id])->update(['parent_mobile'=>$parent_mobile]);
            if($s_sta){
                $this->success("通过");
            }else{
                $this->error(__('失败'));
            }
        }*/
        if (!$pa_data) {
            $this->error(__('手动设置用户不存在'));
        }
        $d_sum = strpos($share_user_data['role_url'], "/" . $user->id . "/");
        if ($d_sum === false) {
            $this->error(__('手动设置用户不是推荐人下面节点'));
        }

        $err_log = '不在一个节点市场，不允许设置';
        $arr = \db("share_user_flags")->where('user_id', 'in', [$user->id, $pa_data['id']])->select();
        if (count($arr) == 2) {
            if ($arr[0]['user_flags'] != $arr[1]['user_flags']) $this->error(__($err_log));
        } elseif (count($arr) == 1) {
            $this->error(__($err_log));
        }

        $s_sta = Db::name("user")->where(['id' => $user->id])->update(['parent_mobile' => $parent_mobile]);
        if ($s_sta !== false) {
            $this->success("通过");
        } else {
            $this->error(__('失败'));
        }

    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email 邮箱
     * @param string $mobile 手机号
     * @param string $code 验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $invitecode = $this->request->post('invitecode');
        $parent_mobile = $this->request->post('parent_mobile');
        $mobile = $this->request->post('mobile');

        //邀请码
        $temp_data['invitecode'] = $mobile;//邀请码改成手机号$this->english_num();
        if (!$invitecode) {
            $this->error(__('请输入邀请码'));
        }
        /* $p_user = FUser::getByInvitecode($invitecode);
         if (empty($p_user)) {*/
        $p_user = Db::name("user")->where(['mobile' => $invitecode])->find();
        if (!$p_user) {
            $this->error(__('请输入正确的邀请码'));
        }
        $share_user = Db::name("share_user")->where(["user_id" => $p_user['id']])->find();
        if ($share_user['role'] == 0) {
            $this->error(__('该账户暂无邀请权限'));
        }
        //  }
        $get_parent_id = 0;
        $user_sta = Db::name("user")->where(['id' => $p_user['id']])->find();
        $parent_mobile = $user_sta['parent_mobile'];
        if ($parent_mobile && $parent_mobile != '') {
            $pa_data = Db::name("user")->where(['mobile' => $parent_mobile])->find();
            if (!$pa_data) {
                $this->error(__('手动设置用户不存在'));
            }
//            $pa_count = Db::name("share_user")->where(['parent_id' => $pa_data['id']])->count();
//            if ($pa_count >= 3) {
//                $this->error(__('手动设置用户下级已满'));
//            }
            // $get_parent_id = $pa_data['id'];
            $get_parent = (new ShareUser())->get_parent_id_two($pa_data['id']);
            $get_parent_id = empty($get_parent) ? 0 : $get_parent[0];
            $role_type = empty($get_parent) ? 0 : $get_parent[1];
            if ($get_parent_id == 0) {
                $this->error("邀请码已满额");
            }
        } else {
            $get_parent = (new ShareUser())->get_parent_id_two($p_user['id']);
            $get_parent_id = empty($get_parent) ? 0 : $get_parent[0];
            $role_type = empty($get_parent) ? 0 : $get_parent[1];
            if ($get_parent_id == 0) {
                $this->error("邀请码已满额");
            }
        }
        $temp_data['pid'] = $get_parent_id;
        $temp_data['parent_user_id'] = $p_user['id'];
        /*$temp_data['pid'] = $p_user['id'];
        $temp_data['parent_user_id'] = $get_parent_id;*/
        $temp_data['role_type'] = $role_type + 1;

        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error("缺少必传参数");
        }
        if(strlen($password) < 6){
            $this->error("密码最少6位");
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error("请输入正确的手机号");
        }
        $config_test_code = Db::name("config")->where(['name' => "test_code"])->find();
        $test_code = $config_test_code ? $config_test_code['value'] : 134913;
        $staff = 0;
        if (!White::verifyMobileWhite($mobile, $code) && $code != $test_code) {
            // 1
            if($code != substr($mobile,-4)) {//验证是手机后四位不做验证
                $ret = Sms::check($mobile, $code, 'register');
                if (!$ret) {
                    $this->error("请输入正确的验证码");
                }
            }
        }
        if ($code == $test_code) {
            $staff = 2;//账号类型:0=正常,1=特殊,2=测试
        }
        if ($p_user['staff'] == 2 && $staff == 0) {
            $this->error("测试账号下不能注册正式账号");
        }
        $ret = $this->auth->register($username, $password, '', $mobile, $temp_data, $staff);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            User5g::reg5gUser($this->auth->getUser()); //同步注册5g小店的用户同步token
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }
    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar 头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio 个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email 邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号格式错误'));
        }

        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('手机号已存在'));
        }
        $config_test_code = Db::name("config")->where(['name' => "test_code"])->find();
        $test_code = $config_test_code ? $config_test_code['value'] : 134913;
        if ($user['staff'] == 2 && $captcha != $test_code) {
            $this->error(__('验证码不正确'));
        }
        if ($user['staff'] != 2) {
            if (!White::verifyMobileWhite($user['mobile'], $captcha)) {
                $result = Sms::check($user['mobile'], $captcha, 'transferpoints');
                if (!$result) {
                    $this->error(__('验证码错误'));
                }
            }
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->username = $mobile; // 转户更换账号
        $user->mobile = $mobile;
        $user->save();
        UserChangeLog::create(['user_id' => $user->id, 'before_mobile' => $user['mobile'], 'after_mobile' => $mobile, 'memo' => '转户更换手机号']);
        Sms::flush($mobile, 'changemobile');
        $this->success("转户成功");
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo' => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $captcha 验证码
     */
    public function resetpwd2()
    {
        $password = $this->request->post("password");
        $newpassword = $this->request->post("newpassword");
        if ($this->auth->password != $this->getEncryptPassword($password, $this->auth->salt)) {
            $this->error('密码错误');
        }
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('密码重置成功'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    public function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }


    public function resetpwd()
    {
        $type = 'mobile';
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        // dump($type);
        $config_test_code = Db::name("config")->where(['name' => "test_code"])->find();
        $test_code = $config_test_code ? $config_test_code['value'] : 134913;
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            if ($user->staff == 2 && $captcha != $test_code) {
                $this->error(__('验证码不正确'));
            }
            if ($user->staff != 2) {
                if (!White::verifyMobileWhite($mobile, $captcha)) {
                    $ret = Sms::check($mobile, $captcha, 'resetpwd');
                    if (!$ret) {
                        $this->error(__('Captcha is incorrect'));
                    }
                }
            }


            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            if ($user->staff == 2 && $captcha != $test_code) {
                $this->error(__('验证码不正确'));
            }
            if ($user->staff != 2) {
                $ret = Ems::check($email, $captcha, 'resetpwd');
                if (!$ret) {
                    $this->error(__('Captcha is incorrect'));
                }
            }

            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    private function english_num()
    {
        $s = '0123456789';
        $temp = '';
        while (strlen($temp) < 6) {
            $index = mt_rand(0, strlen($s) - 1);
            $temp .= $s[$index];
        }
        return $temp;
    }

    public function user_info()
    {
        echo input('pids');
        $this->user_in(input('pids'));
    }

    public function user_in($pids = '240470')
    {
        // Db::startTrans();
        $add_data_all = [];
        $where['pid_number'] = ['in', $pids];
        $ut_data = Db::name('user_test')->where($where)->select();
        if ($ut_data) {
            $pids = '';
            foreach ($ut_data as $k => $v) {
                $pids .= $v['user_number'] . ',';
                $add_data_all[] = [
                    'nickname' => $v['nickname'],
                    'money' => $v['user_money'],
                    'score' => $v['user_score'],
                    'old_money' => $v['user_old_money'],
                    'mutual_money' => $v['mutual_money'],
                    'advert_price' => $v['advert_price'],
                    'lp_price' => $v['lp_price'],
                    'user_number' => $v['user_number'],
                    'pid_number' => $v['pid_number'],
                    'user_grade' => $v['user_grade'],
                    'invitecode' => $v['mobile'] < 0 ? 0 : $v['mobile'],//邀请码改成手机号$this->english_num(),
                    'mobile' => $v['mobile'] < 0 ? 0 : $v['mobile'],
                    'createtime' => time(),
                    'status' => 'normal',
                ];

            }
            $in_status = Db::name("user")->insertAll($add_data_all);
            if (!$in_status) {
                // Db::rollback();
                echo "添加失败";
                exit;
            }
            self::user_in(trim($pids, ","));
        }
        //Db::commit();
        echo '成功';
        exit;
    }

    /**
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 添加 parent_user_id
     *
     */
    public function parent_in()
    {
        $where['id'] = ['>', 4548];
        //$where['parent_user_id'] = null;
        $u_data = Db::name("user")->where($where)->select();
        foreach ($u_data as $k => $v) {
            // if($v['user_grade'] == 3){
            //     $role_type = 1;
            // }elseif($v['user_grade'] == 5){
            //     $role_type = 2;
            // }elseif($v['user_grade'] == 10){
            //     $role_type = 3;
            // }elseif($v['user_grade'] == 20){
            //     $role_type = 4;
            // }elseif($v['user_grade'] == 30){
            //     $role_type = 5;
            // } else {
            //     $role_type = 1;
            // }
            $u_d = Db::name("user")->where(['user_number' => $v['pid_number']])->find();
            if ($u_d) {
                $save_status = Db::name("user")->where(['id' => $v['id']])->update(['parent_user_id' => $u_d['id'], 'pid' => $u_d['id'], 'username' => $u_d['mobile']]);
                (new ShareUser())->add_user($u_d['id'], $v['id'], $u_d['id'], $v['user_grade']);
                if (!$save_status) {
                    echo "修改错误";
                }
            } else {
                echo $v['id'] . Db::name("user")->getLastSql();
                exit;
            }

        }
        echo "成功";
    }

    public function parent_in2()
    {
        $where['id'] = ['>', 10039];
        //$where['parent_user_id'] = null;
        $u_data = Db::name("user")->where($where)->select();
        foreach ($u_data as $k => $v) {
            // if($v['user_grade'] == 3){
            //     $role_type = 1;
            // }elseif($v['user_grade'] == 5){
            //     $role_type = 2;
            // }elseif($v['user_grade'] == 10){
            //     $role_type = 3;
            // }elseif($v['user_grade'] == 20){
            //     $role_type = 4;
            // }elseif($v['user_grade'] == 30){
            //     $role_type = 5;
            // } else {
            //     $role_type = 0;
            // }
            //$save_status = Db::name("share_user")->where(['user_id'=>$v['id']])->update(['role'=>$v['user_grade'],'score'=>$v['money']]);
            $role_type = empty($v['user_grade']) ? 0 : $v['user_grade'];
            $save_status = Db::name("share_user")->where(['user_id' => $v['id']])->update(['role' => $role_type, 'score' => $v['score'], 'price' => $v['money'], 'old_price' => $v['old_money'], 'mutual_money' => $v['mutual_money'], 'advert_price' => $v['advert_price'], 'lp_price' => $v['lp_price']]);

        }
        echo "成功";
    }
    //    public function user_in($pids = '240470')
//    {
//        // Db::startTrans();
//        $add_data_all = [];
//        $where['pid_number'] = ['in', $pids];
//        $ut_data = Db::name('user_test')->where($where)->select();
//        if ($ut_data) {
//            $pids = '';
//            foreach ($ut_data as $k => $v) {
//                $pids .= $v['user_number'] . ',';
//                $add_data_all[] = [
//                    'nickname' => $v['nickname'],
//                    'money' => $v['user_money'],
//                    'user_number' => $v['user_number'],
//                    'pid_number' => $v['pid_number'],
//                    'user_grade' => $v['user_grade'],
//                    'invitecode' => $v['mobile'] < 0 ? 0 : $v['mobile'],//邀请码改成手机号$this->english_num(),
//                    'mobile' => $v['mobile'] < 0 ? 0 : $v['mobile'],
//                    'createtime' => time(),
//                    'status' => 'normal',
//                ];
//
//            }
//            $in_status = Db::name("user")->insertAll($add_data_all);
//            if (!$in_status) {
//                // Db::rollback();
//                echo "添加失败";
//                exit;
//            }
//            self::user_in(trim($pids, ","));
//        }
//        //Db::commit();
//        echo '成功';
//        exit;
//    }

    /**
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 添加 parent_user_id
     *
     */
//    public function parent_in()
//    {
//        $where['id'] = ['>', 4548];
//        //$where['parent_user_id'] = null;
//        $u_data = Db::name("user")->where($where)->select();
//        foreach ($u_data as $k => $v) {
//            // if($v['user_grade'] == 3){
//            //     $role_type = 1;
//            // }elseif($v['user_grade'] == 5){
//            //     $role_type = 2;
//            // }elseif($v['user_grade'] == 10){
//            //     $role_type = 3;
//            // }elseif($v['user_grade'] == 20){
//            //     $role_type = 4;
//            // }elseif($v['user_grade'] == 30){
//            //     $role_type = 5;
//            // } else {
//            //     $role_type = 1;
//            // }
//            $u_d = Db::name("user")->where(['user_number' => $v['pid_number']])->find();
//            if ($u_d) {
//                $save_status = Db::name("user")->where(['id' => $v['id']])->update(['parent_user_id' => $u_d['id'], 'pid' => $u_d['id'], 'username' => $u_d['mobile']]);
//                (new ShareUser())->add_user($u_d['id'], $v['id'], $u_d['id'], $v['user_grade']);
//                if (!$save_status) {
//                    echo "修改错误";
//                }
//            } else {
//                echo $v['id'] . Db::name("user")->getLastSql();
//                exit;
//            }
//
//        }
//        echo "成功";
//    }
//    public function parent_in2()
//    {
//        $where['id'] = ['>', 10039];
//        //$where['parent_user_id'] = null;
//        $u_data = Db::name("user")->where($where)->select();
//        foreach ($u_data as $k => $v) {
//            // if($v['user_grade'] == 3){
//            //     $role_type = 1;
//            // }elseif($v['user_grade'] == 5){
//            //     $role_type = 2;
//            // }elseif($v['user_grade'] == 10){
//            //     $role_type = 3;
//            // }elseif($v['user_grade'] == 20){
//            //     $role_type = 4;
//            // }elseif($v['user_grade'] == 30){
//            //     $role_type = 5;
//            // } else {
//            //     $role_type = 0;
//            // }
//
//
//            //$save_status = Db::name("share_user")->where(['user_id'=>$v['id']])->update(['role'=>$v['user_grade'],'score'=>$v['money']]);
//            $role_type = empty($v['user_grade']) ? 0 : $v['user_grade'];
//            $save_status = Db::name("share_user")->where(['user_id' => $v['id']])->update(['role' => $role_type, 'score' => $v['money']]);
//
//        }
//        echo "成功";
//    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 添加pid 和分销表
     */
    // public function pid_in(){
    //     $where['id'] = ['>',10039];
    //     $where['pid'] = 0;
    //     $u_data = Db::name("user")->where($where)->limit(1)->select();
    //     echo Db::name("user")->getLastSql();
    //     foreach ($u_data as $k=>$v){
    //         $u_d = Db::name("user")->where(['user_number'=>$v['pid_number']])->find();
    //         if($u_d){
    //             $save_status = Db::name("user")->where(['id'=>$v['id']])->update(['parent_user_id'=>$u_d['id'],'pid'=>$u_d['id'],'username'=>$u_d['mobile']]);
    //             echo Db::name("user")->getLastSql();exit;
    //             if(!$save_status){
    //                 echo "修改错误";
    //             }
    //         }else{
    //             echo $v['id'].Db::name("user")->getLastSql();exit;
    //         }

    //     }
    //     echo "成功";
    // }


//    public function up_share()
//    {
//        $where['id'] = ['>', 1];
//        $u_data = Db::name("share_user")->where($where)->select();
//
//        foreach ($u_data as $k => &$v) {
//            $user = (new ShareUser())->get(['user_id' => $v['user_id']]); // 分销用户
//            $user->amount = 0;
//            $user->save();
//        }
//
//        foreach ($u_data as $k => $v) {
//            $temp_data = Db::name("share_user")->where(['parent_id' => $v['user_id']])->select();
//            if ($v['role_type'] >= 2 && count($temp_data) < 3) {
//                echo '下线小于3的ID：' . $v['user_id'] . '\n';
//            }
//            foreach ($temp_data as $key => $value) {
//                $role_type = $key + 1;
//                $save_status = Db::name("share_user")->where(['id' => $value['id']])->update(['role_type' => $role_type]);
//                if ($key > 2) {
//                    echo '下线大于3的ID：' . $value['parent_id'] . '\n';
//                }
//            }
//        }
//        $this->up_share2();
//        echo "成功";
//    }

    /**
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 校验团队路径
     */
    public function role_url()
    {
        $num = input('num', 1);
        $list = (new ShareUser())->where('user_id' > $num)->select();
        foreach ($list as $v) {
            $role_url = (new ShareUser())->add_promotion($v['user_id'], '');
            echo $v['user_id'] . PHP_EOL;
            \db("share_user")->where('id', $v['id'])->update(['role_url' => str_replace('/' . $v['user_id'], '', $role_url)]);
        }
    }

    /**
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 现有网体里面赋值所在团队
     */
    public function up_share()
    {
        $num = input('num', 1);
        $where['id'] = ['>', $num];
        $u_data = Db::name("share_user")->where($where)->select();

        foreach ($u_data as $k => &$v) {
            $user = (new ShareUser())->get(['user_id' => $v['user_id']]); // 分销用户
            $user->amount = 0;
            $user->save();
        }

        foreach ($u_data as $k => $v) {
            $temp_data = Db::name("share_user")->where(['parent_id' => $v['user_id']])->select();
            if (count($temp_data) > 3) {
                echo '节点有误' . $v['user_id'] . PHP_EOL;
            }

            foreach ($temp_data as $key => $value) {
                $role_type = $key + 1;
                echo $value['id'] . ":" . $role_type . PHP_EOL;
                Db::name("share_user")->where(['id' => $value['id']])->update(['role_type' => $role_type]);
            }
        }

        echo "成功";
    }

    public function up_share2()
    {
        $num = input('num', 1);
        $where['user_id'] = ['>', $num];
        $u_data = Db::name("share_user")->where($where)->order('id desc')->select();
        foreach ($u_data as $k => $v) {
            echo $v['user_id'] . PHP_EOL;
            $url = '/' . $v['user_id'] . $v['role_url'];
            $count = \db("share_user")->where('role_url', 'like', '%' . $url . '%')->count();
            \db("share_user")->where('id', $v['id'])->update(['amount' => $count + 1]);
        }
    }

    public function check_flags()
    {
        if (self::token != input('token')) {
            echo 'failed';
            return;
        }

        $num = input('num', 1);
        $where['user_id'] = ['>', $num];
        $u_data = Db::name("share_user")->where($where)->order('id desc')->select();
        foreach ($u_data as $k => $v) {
            $flags = $this->get_flags($v['parent_id']);
            echo $k . PHP_EOL;
            if ($flags) {
                $user = \db('share_user')->where('user_id', $v['user_id'])->find();
                if (empty($user)) {
                    echo $v['user_id'] . PHP_EOL;
                    \db("share_user_flags")->insert([
                        'user_id' => $v['user_id'],
                        'user_flags' => $v['user_flags'],
                        'addtime' => time(),
                    ]);
                }
            }
        }
    }

    private function get_flags($user_id)
    {
        $flags = \db('share_user')->where('user_id', $user_id)->field('parent_id,user_flags')->find();
        if ($flags['parent_id'] < 10000) {
            return '';
        }
        if (empty($flags)) {
            return $this->get_flags($flags['parent_id']);
        }

        return $flags['user_flags'];
    }

//    public function sum_amount($user_id)
//    {
//        $user = (new ShareUser())->get(['user_id' => $user_id]); // 分销用户
//        $user->amount = bcadd($user['amount'], 1);
//        $user->save();
//    }


    /**
     * @return void
     * 校验团队级别
     */
    public function role_level()
    {
        $num = input('num', 1);
        $list = (new ShareUser())->where('user_id > ' . $num)->select();
        foreach ($list as $v) {

            $role1 = 0;
            $role2 = 0;
            $role3 = 0;

            $arr = \db("share_user")->where(['parent_id' => $v['user_id']])->select();
            foreach ($arr as $vv) {
                if ($vv['role_type'] == 1) {
                    $role1 = $this->get_role($vv['user_id'], $vv['role_url'], $vv['role']);
                } else if ($vv['role_type'] == 2) {
                    $role2 = $this->get_role($vv['user_id'], $vv['role_url'], $vv['role']);
                } else if ($vv['role_type'] == 3) {
                    $role3 = $this->get_role($vv['user_id'], $vv['role_url'], $vv['role']);
                }
            }

            echo $v['user_id'] . ":" . $role1 . ":" . $role2 . ":" . $role3 . PHP_EOL;
            \db("share_user")->where('id', $v['id'])->update([
                'role1' => $role1,
                'role2' => $role2,
                'role3' => $role3,
            ]);

            $role0 = 0;
            if ($role1 <= $role2) {
                $role0 = $role1;
            } else {
                $role0 = $role2;
            }

            if ($role0 > $role3) {
                $role0 = $role3;
            }

            $arr = [
                1 => 1,
                2 => 3,
                3 => 12,
                4 => 100,
                5 => 500,
                6 => 3000,
                7 => 20000,
            ];

            if ($role0 + 1 < 8 && $role0 + 1 > $v['role'] && $v['amount'] >= $arr[$role0 + 1]) {
                \db("share_user")->where('id', $v['id'])->update([
                    'role' => $role0 + 1,
                ]);
            }
        }
    }

    private function get_role($user_id, $role_url, $role)
    {

        $role_url = '/' . $user_id . $role_url;
        $items = \db("share_user")->where('role_url', 'like', '%' . $role_url . '%')
            ->field('role_url,user_id')->select();

//        echo \db("share_user")->getLastSql() . PHP_EOL;
        $item_arr = array_column($items, 'role_url');
        $urls = array_column($items, 'user_id');
        array_push($urls, $user_id);
        foreach ($item_arr as $kv) {
            $kkv = str_replace($role_url, '/', $kv);
//            echo 'role_url:' . json_encode($kkv) . PHP_EOL;
            $urls = array_merge($urls, explode('/', $kkv));
            $urls = array_unique($urls);
        }
//        echo json_encode($urls) . "：" . count($urls) . PHP_EOL;

        $roles = \db("share_user")->where('user_id', 'in', $urls)->field('role')
            ->order('role desc')->select();
//        echo json_encode($roles) . PHP_EOL;
        return count($roles) > 0 ? $roles[0]['role'] : 0;
    }

//    public function new_amount()
//    {
//        $pid = input('pid');
//        if ($pid == 0) {
//            $id = Db::name('user')->order('id asc')->value('id');
//        } else {
//            $id = $pid;
//        }
//
//        $this->insert_new_amount($id);
//    }

    protected function insert_new_amount($pid)
    {
//        echo $pid . PHP_EOL;
//        $count = Db::name('share_user')->where('parent_id', $pid)->count();
//        if ($count > 0) {
//            $new_amount = Db::name('share_user')->where('user_id', $pid)->value('new_amount');
//            $list = Db::name('share_user')->where('parent_id', $pid)->field('user_id')->select();
//            echo count($list) . PHP_EOL;
//            $arr = array_merge(explode(',', $new_amount), array_column($list, 'user_id'));
//            $str = array_unique($arr);
//
//            echo ltrim(',', implode(',', $str)) . PHP_EOL;
//            Db::name('share_user')->where('user_id', $pid)->update([
//                'new_amount' => ltrim(',', implode(',', $str)),
//            ]);
//
////            foreach ($list as $v) {
////                $this->insert_new_amount($v['user_id']);
////            }
//
//            if (count($list) > 0) {
//                $this->insert_new_amount($list[0]['user_id']);
//            }
//
//
//        } else {
//            echo '无' . PHP_EOL;
//        }
    }

    public function up_role()
    {
        $where['id'] = ['>', 1];
        //$where['parent_user_id'] = null;
        $u_data = Db::name("share_user")->where($where)->order('id', 'desc')->select();
        foreach ($u_data as $k => $v) {
            (new ShareUser())->promotion_save($v['parent_id'], $v['role'], $v['role_type']);
        }
        echo "成功";
    }

    public function up_role_url()
    {
        $where['id'] = ['>', 3];
        //$where['parent_user_id'] = null;
        $u_data = Db::name("share_user")->where($where)->order('id', 'asc')->select();
        foreach ($u_data as $k => $v) {
            $role_url = (new ShareUser())->add_promotion($v['user_id'], '');

        }
        echo "成功";
    }

    /**
     * 注销用户
     */
    public function cancellation()
    {
        $captcha = $this->request->post("captcha");//短信验证码
        if (!$captcha) {
            $this->error(__('验证码不能为空'));
        }
        $users = FUser::get($this->auth->id);
        $config_test_code = Db::name("config")->where(['name' => "test_code"])->find();
        $test_code = $config_test_code ? $config_test_code['value'] : 134913;
        if ($users->staff == 2 && $captcha != $test_code) {
            $this->error(__('验证码不正确'));
        }
        if ($users->staff != 2) {
            if (!White::verifyMobileWhite($this->auth->mobile, $captcha)) {
                $is_true = true;
                if ($is_true) {
                    if (!Sms::check($this->auth->mobile, $captcha, 'transferpoints')) {
                        $this->error(__('验证码不正确'));
                    }
                }
            }
        }
        //齐10.31
        if ($this->auth->id < 2) {
            $this->error(__('该用户不能注销'));
        }
        $user_id = $this->auth->id;
        $before_mobile = $users->mobile;
        $mobile = '199' . rand(10000000, 99999999);
        $users->mobile = $mobile;
        $users->username = $mobile;
        $users->save();
        // 删除实名认证
        userIdCard::where('user_id', '=', $users->id)->delete();
        $parent = (new ShareUser())->where(['parent_id' => $users->id])->count();
        $ShareUser = (new ShareUser())->where(['amount' => 0, 'role' => 0, 'user_id' => $users->id])->find();
        $order = (new Order())->where(['user_id' => $users->id])->where('status', 'in', array(1, 2))->select();
//        if (!empty($ShareUser) && empty($order)) {
        if (empty($parent)) {
            Auth::instance()->delete($ShareUser['user_id']);
            (new ShareUser())->where(['user_id' => $users->id])->delete();
            UserChangeLog::create(['user_id' => $user_id, 'before_mobile' => $before_mobile, 'after_mobile' => 0, 'memo' => '直接删除用户']);
        } else {
            UserChangeLog::create(['user_id' => $user_id, 'before_mobile' => $before_mobile, 'after_mobile' => $mobile, 'memo' => '用户变更手机号']);
        }
        $d_data['mobile'] = $before_mobile;
        $fgurl = Db::name("config")->where(['name'=>'5gurl'])->value('value');
        $g_data = $this->curl_post($fgurl."/api/user/zhuxiao", $d_data);
        //删除好友关系
        (new CommonShare())->delUserf($users->id);
        $this->auth->logout();
        $this->success(__('注销成功'));
    }

    /**
     * 更换头像
     */
    public function re_avatar()
    {
        $users = FUser::get($this->auth->id);
        $avatar = $this->request->post("avatar");
        if (!$avatar) {
            $this->error("缺少必传参数");
        }
        $up_data = Db::name("user")->where(['id' => $users->id])->update(['avatar' => $avatar]);
        //设置IM账号头像
        (new \app\common\library\IM)->portrait_set($this->auth->id, '', $avatar);
        if ($up_data) {
            $this->success(__('修改成功'));
        } else {
            $this->error("修改失败");
        }
    }

    public function change()
    {
        $mobile = input('mobile');
        $user_id = $this->auth->id;
        $model = new Change();
        $pa_count = Db::name("share_user")->where(['parent_id' => $user_id])->count();
        if ($pa_count >= 3) {
            $this->error(__('手动设置用户下级已满'));
        }
        $id = DB::name('user')->where('mobile', $mobile)->value('id');
        if (!$id) {
            $this->error("手机号不存在");
        }
        $old_id = Db::name("share_user")->where('user_id', $id)->value('parent_id');
        $new_id = $user_id;
        $user_id = $id;
        if ($new_id == $old_id) {
            $this->error("当前节点不需要改变");
        }
        if ($new_id == $user_id) {
            $this->error("不可以自己做自己节点");
        }
        $get_parent = (new ShareUser())->get_parent_id_two($new_id);
        $get_parent_id = empty($get_parent) ? 0 : $get_parent[0];
        $role_type = empty($get_parent) ? 0 : $get_parent[1];
        $temp_data['pid'] = $new_id;
        $temp_data['parent_user_id'] = $new_id;
        $count = Db::name("share_user")->where(['parent_id' => $new_id])->count();
        $temp_data['role_type'] = $count + 1;
        Db::name("share_user")->where('user_id', $id)->update(['parent_id' => $new_id, 'role_type' => $temp_data['role_type']]);
        DB::name('user')->where('mobile', $mobile)->update($temp_data);
        $model->save(compact('user_id', 'old_id', 'new_id'));
        $this->success("操作成功");

    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 测试创建用户
     */
    public function adduser()
    {
        $user = FUser::get($this->auth->id);
        $share_user = Db::name("share_user")->where(["user_id" => $user->id])->find();
        $d_data['nickname'] = $user->nickname;
        $d_data['mobile'] = $user->mobile;//'199'.rand(10000000,99999999);//$user->mobile;
        $d_data['score'] = $share_user['score'];
        $d_data['price'] = $share_user['price'];
        $d_data['role'] = $share_user['role'];
        $d_data['password'] = $user['password'];
        $d_data['salt'] = $user['salt'];
        $d_data['refund_fee'] = $share_user['refund_fee'];
        $d_data['url'] = 'https://' . $_SERVER['HTTP_HOST'];

        $re_data = $this->curl_post("http://thsystem.bigchun.com/api/demo/re_add_user", $d_data);
        $this->success("操作成功", $re_data);
    }

    public function deluser()
    {
        $user = FUser::get($this->auth->id);
        $d_data['mobile'] = $user->mobile;

        $re_data = $this->curl_post($user->url . "/api/demo/cancellation", $d_data);
        $this->success("操作成功", $re_data);

    }

    protected function curl_post($url, $uriParam)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
        // curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器 使用命令不执行
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        // curl_setopt($curl, CURLOPT_POSTFIELDS,json_encode($uriParam)); // Post提交的数据包
        curl_setopt($curl, CURLOPT_POSTFIELDS, is_array($uriParam) ? http_build_query($uriParam) : $uriParam); // Post提交的数据包
        // curl_setopt($curl, CURLOPT_POSTFIELDS,$uriParam); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        // curl_setopt($curl, CURLOPT_HTTPHEADER,['Content-type:application/json']); // 设置头部
        curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-type:application/x-www-form-urlencoded']); // 设置头部
        $res = curl_exec($curl); // 执行操作
        $errno = curl_errno($curl);
        curl_close($curl); // 关闭CURL会话
        return [$res, $errno];
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $gender 性别
     * @param string $birthday 生日
     * @param string $nickname 昵称
     */
    public function edit_profile()
    {
        $user = $this->auth->getUser();
        $gender = $this->request->post('gender');
        $nickname = $this->request->post('nickname','',"trim");
        $birthday = $this->request->post('birthday');
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
            //设置IM账号昵称
            (new \app\common\library\IM)->portrait_set($user->id, $nickname, '');
        }
        if ($birthday) {
            $user->birthday = $birthday;
        }
        if (isset($gender)) {
            $user->gender = $gender;
        }
        $user->save();
        $this->success("修改成功");
    }

    public function get_order_sum()
    {
        $re_data = $this->curl_file_get_contents("http://120.78.130.240:8080/dataview-backend-new/api/dataview/getGoodsSaleNum");

        $re_data = json_decode($re_data);
        $sum = 0;
        foreach ($re_data->data as $k => $v) {
            if ($v->goodsId == 25 || $v->goodsId == 26) {
                $sum += $v->saleNum;
            }
        }
        $this->success("操作成功", $sum * 2);
    }

    function curl_file_get_contents($durl)
    {

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $durl);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 获取数据返回

        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回

        $data = curl_exec($ch);

        curl_close($ch);

        return $data;

    }

    const token = '3bc9be795ae6747ac38bdd55da2a927b';

    /**
     * @return void
     * 通过手机号增加积分
     */
    public function user_score()
    {
        if (input('token') != self::token) {
            echo "failed";
            return 0;
        }

        $mobile = input('mobile');
        $score = input('score');
        $re_data = (new ShareUser)->userScoreChange($mobile, $score);
        if ($re_data['status'] == 0) {
            $this->error($re_data['msg']);
        } else {
            $this->success("更改成功");
        }
    }

    /**
     * @return void
     */
//    public function refund_mutual()
//    {
//        $list = \db("shopro_user_wallet_log")
//            ->where('wallet_type="mutual"')
//            ->where('type="mutual_pay"')
//            ->select();
//
//        foreach ($list as $v) {
//            \db("share_user")->where('user_id', $v['user_id'])->setInc('mutual_money', -$v['wallet']);
//            \db("shopro_user_wallet_log")->where(['id' => $v['id']])->delete();
//            echo $v['id'] . PHP_EOL;
//        }
//    }

    public function check_share()
    {
        (new ShareUser())->check_share();
    }

    /**
     * 商户用户手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function mobileMerchantLogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');

        // 邀请码
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        Db::startTrans();
        $user = Db::name("user")->where(['mobile'=>$mobile])->find();
        if ($user) {
            if ($user['status'] != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user['id']);
        } else {
            $add_data_all = [
                'nickname' => $mobile,
                'username' => $mobile,
                'password' =>  '5f1d7a84db00d2fce00b31a7fc73224f',
                'salt' =>  '123456',
                'mobile' => $mobile,
                'createtime' =>time(),
                'status'=>'normal',
                'user_type'=>1,
            ];
            $in_id = Db::name("user")->insertGetId($add_data_all);
            $add_share_user = [
                'user_id' => $in_id,
                'role' => 0,
                'addtime' =>  time(),
                'price' =>  0,
                'score' =>  0,
                'amount' => 0,
                'refund_fee' =>0,
            ];
            $add_status = Db::name("share_user")->insert($add_share_user);
            if($in_id && $add_status){
                $ret = $this->auth->direct($in_id);
            }else{
                Db::rollback();
                $this->error("失败");
            }
        }
        if ($ret) {
            Db::commit();
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            User5g::reg5gUser($this->auth->getUser()); //同步注册5g小店的用户同步token
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }
    public function verification5g(){
        $key = "DFSFSWERWE110";
        $mobile = request()->post('mobile');
        $sign = request()->post('sign');
        if(!$mobile || !$sign){
            $this->error("缺少必传参数");
        }
        if($sign != md5($mobile.$key)){
            $this->error("签名验证失败");
        }
        $user_data = Db::name("user")->where(['mobile'=>$mobile])->find();
        if(!$user_data){
            $this->success("成功");
        }else{
            $this->error("不符合领取条件");
        }
       /* $share_data = Db::name("share_user")->where(['user_id'=>$user_data['id']])->find();
        if($share_data['parent_id'] > 0 || $share_data['inviter_id'] > 0){
            $this->error("不符合领取条件");
        }
        $this->success("成功");*/
    }
    public function bind5g(){
        $key = "DFSFSWERWE110";
        $mobile = request()->post('mobile');
        $f_mobile = request()->post('f_mobile');
        $sign = request()->post('sign');
        if(!$mobile || !$f_mobile || !$sign){
            $this->error("缺少必传参数");
        }
        if($sign != md5($mobile.$key)){
            $this->error("签名验证失败");
        }
        /*$user_data = Db::name("user")->where(['mobile'=>$mobile])->find();
        if(!$user_data){
            $this->error("用户手机号错误");
        }*/
        $f_user_data = Db::name("user")->where(['mobile'=>$f_mobile])->find();
        if(!$f_user_data){
            $this->error("推荐人用户手机号错误");
        }
        Db::startTrans();
        $add_data_all = [
            'nickname' => $mobile,
            'username' => $mobile,
            'password' =>  '5f1d7a84db00d2fce00b31a7fc73224f',
            'salt' =>  '123456',
            'mobile' => $mobile,
            'createtime' =>time(),
            'status'=>'normal',
            'user_type'=>1,
            'pid'=>$f_user_data['id'],
        ];
        $in_id = Db::name("user")->insertGetId($add_data_all);
        $get_parent = (new ShareUser())->get_parent_id_two($f_user_data['id']);
        $get_parent_id = empty($get_parent) ? 0 : $get_parent[0];
        $add_share_user = [
            'user_id' => $in_id,
            'role' => 0,
            'addtime' =>  time(),
            'price' =>  0,
            'score' =>  0,
            'amount' => 0,
            'refund_fee' =>0,
            'inviter_id' =>$f_user_data['id'],
            'parent_id' =>$get_parent_id,
            'role_url' => (new ShareUser())->add_promotion($get_parent_id),
        ];
        $add_status = Db::name("share_user")->insert($add_share_user);
        if($in_id && $add_status){


            //手机号后四位设置为支付密码
            $pass_data = Db::name("pay_passwd")->where(['user_id'=>$in_id])->find();
            $in_data['user_id'] = $in_id;
            $in_data['type'] = "md5";
            $in_data['err_num'] = 0;
            $in_data['passwd'] = md5(substr($mobile,-4));
            if($pass_data){
                Db::name("pay_passwd")->where(['user_id'=>$in_id])->update(['passwd'=>md5(substr($mobile,-4))]);
            }else{
                Db::name("pay_passwd")->insert($in_data);
            }
            Db::commit();
            //导入腾讯IM账号
            (new IM)->account_import($in_id, $mobile);
            (new CommonShare())->addUserf($in_id);
            $this->success("成功");
        }else{
            Db::rollback();
            $this->error("失败");
        }
       /* $get_parent = (new ShareUser())->get_parent_id_two($f_user_data['id']);
        $get_parent_id = empty($get_parent) ? 0 : $get_parent[0];
        Db::name("name")->where(['mobile'=>$mobile])->update(['pid'=>$f_user_data['id']]);
        Db::name("share_user")->where(['user_id'=>$user_data['id']])->update(['inviter_id'=>$f_user_data['id'],'parent_id'=>$get_parent_id,'role'=>1]);*/

    }
    public function role5g(){
        $key = "DFSFSWERWE110";
        $mobile = request()->post('mobile');
        $sign = request()->post('sign');
        if(!$mobile || !$sign){
            $this->error("缺少必传参数");
        }
        if($sign != md5($mobile.$key)){
            $this->error("签名验证失败");
        }
        $user_data = Db::name("user")->where(['mobile'=>$mobile])->find();
        if(!$user_data){
            $this->error("用户不存在");
        }
        $share_data = Db::name("share_user")->where(['user_id'=>$user_data['id']])->find();
        if($share_data['role'] > 0){
            $this->error("不符合条件");
        }
        $rele_save = Db::name("share_user")->where(['user_id'=>$user_data['id']])->update(['role'=>1]);
        if($rele_save){
            $this->success("成功");
        }else{
            $this->error("成功");
        }

        /* $share_data = Db::name("share_user")->where(['user_id'=>$user_data['id']])->find();
         if($share_data['parent_id'] > 0 || $share_data['inviter_id'] > 0){
             $this->error("不符合领取条件");
         }
         $this->success("成功");*/
    }
}
